package com.lagou;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MyProcessor extends BaseRegionObserver {

    @Override
    public void postDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException {
        //获取表
        Table e2 = e.getEnvironment().getTable(TableName.valueOf("e2"));
        //获取行号
        byte[] u1 = delete.getRow();
        Set<Map.Entry<byte[], List<Cell>>> entries = delete.getFamilyCellMap().entrySet();
        for (Map.Entry<byte[], List<Cell>> entry : entries) {
            for (Cell cell : entry.getValue()) {
                byte[] u2 = CellUtil.cloneQualifier(cell);
                //获取目标用户，判断防止无限迭代
                if (e2.exists(new Get(u2).addColumn(Bytes.toBytes("friends"),u1))){
                    Delete delete1 = new Delete(u2);
                    delete1.addColumn(Bytes.toBytes("friends"),u1);
                    e2.delete(delete1);
                }
            }
        }
        e2.close();
            }
}
